#include "../../include/mysql/loginmysql.h"

LoginMysql::LoginMysql()
{
}

LoginMysql::~LoginMysql()
{
}

bool LoginMysql::userIsInMysql(const std::shared_ptr<User> &user)
{
    WFMySQLTask *task = WFTaskFactory::create_mysql_task(kMysql_url, 1, mysql_callback);
    std::stringstream query;
    query << R"(select * from user where user_name=")";
    query << user->getUserName();
    query << R"(" and user_pwd=")";
    query << user->getUserPwd();
    query << R"(")";
    std::cout << query.str() << std::endl;
    task->user_data = this;
    task->get_req()->set_query(query.str());
    task->start();
    std::unique_lock<std::mutex> lck(locker);
    while (!isFinished)
        vb.wait(lck);
    return user_is_in_mysql;
}

void LoginMysql::mysql_callback(WFMySQLTask *task)
{
    LoginMysql *self = (LoginMysql *)task->user_data;
    self->isFinished = true;
    if (task->get_state() != WFT_STATE_SUCCESS)
    {
        self->vb.notify_one();
        return;
    }
    if (task->get_resp()->get_packet_type() == MYSQL_PACKET_HEADER_ERROR)
    {
        std::cout << task->get_resp()->get_error_code() << ' ' << task->get_resp()->get_error_msg().c_str() << std::endl;
        self->vb.notify_one();
        return;
    }
    protocol::MySQLResultCursor cursor(task->get_resp());
    std::vector<std::vector<protocol::MySQLCell>> rows;
    cursor.fetch_all(rows);
    if (rows.size() == 1)
        self->user_is_in_mysql = true;
    self->vb.notify_one();
}